package com.shanghaionstar.utils;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;

import com.shanghaionstar.R;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;



/**
 * Created by Rengui Lu on 2016/6/7.
 */
public class AppStoreUtil {

//    private static final String P_N = "com.shanghaionstar";

    public static void jumpToStore(Context context, String packageName) {
        if (Build.MANUFACTURER.contains("HTC")) {
            Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setPackage(packageName);
            context.startActivity(intent);
        }
    }


    // 获取列表
    public static Map<String, String> getAvilibleStores(Context context) {
        String[] mPackages = {"com.wandoujia.phoenix2",
                "cn.goapk.market", "com.huawei.appmarket",
                "com.91.appmarket", "com.qihoo.appstore",
                "com.tencent.android.qqdownloader", "com.baidu.appsearch",
                "com.xiaomi.market"};
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        Map<String, String> mAppStores = new LinkedHashMap<String, String>();
        if (pinfo != null) {
            iteratePackageInfo(mPackages, packageManager, pinfo, mAppStores);
        }
        return mAppStores;
    }

    private static void iteratePackageInfo(String[] mPackages, PackageManager packageManager, List<PackageInfo> pinfo, Map<String, String> mAppStores) {
        for (int i = 0; i < pinfo.size(); i++) {
            String pn = pinfo.get(i).packageName;
            String appName = (String) packageManager.getApplicationLabel(pinfo.get(i).applicationInfo);
            for (String packName : mPackages) {
                addCheck(mAppStores, pn, appName, packName);
            }
        }
    }

    private static void addCheck(Map<String, String> mAppStores, String pn, String appName, String packName) {
        if (pn.contains(packName)) {
            if (mAppStores.containsKey(packName)) {
                String oriName = mAppStores.get(packName);
                mAppStores.put(packName, oriName.length() > appName.length() ? appName : oriName);
            } else {
                mAppStores.put(packName, appName);
            }
        }
    }

    public static void showDia(final Context context) {
        Observable.just(AppStoreUtil.getAvilibleStores(context))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Func1<Map<String, String>, Boolean>() {
                    @Override
                    public Boolean call(Map<String, String> stringStringMap) {
                        return stringStringMap != null;
                    }
                }).subscribe(new Action1<Map<String, String>>() {
            @Override
            public void call(Map<String, String> stringStringMap) {
                final String[] items = getStoreNames(stringStringMap);
                createDialog(context, stringStringMap, items);
            }
        });
//        final Map<String, String> mAppStores = AppStoreUtil.getAvilibleStores(context);
//        if (mAppStores != null) {
//            final String[] items = getStoreNames(mAppStores);
//            createDialog(context, mAppStores, items);
//        }
    }

    @NonNull
    private static String[] getStoreNames(Map<String, String> mAppStores) {
        Collection<String> mNames = mAppStores.values();
        final String[] items = new String[mNames.size()];
        mNames.toArray(items);
        return items;
    }

    private static void createDialog(final Context context, final Map<String, String> mAppStores, final String[] items) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.app_store_sel);
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                String packName = getPackName(which, items, mAppStores);
                AppStoreUtil.jumpToStore(context, packName);
            }
        };
        builder.setItems(items, listener);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private static String getPackName(int which, String[] items, Map<String, String> mAppStores) {
        String appName = items[which];
        Set<String> keys = mAppStores.keySet();
        String packName = "";
        for (String ks : keys) {
            if (appName.equals(mAppStores.get(ks))) {
                packName = ks;
                break;
            }
        }
        return packName;
    }


}
